<?php
require_once 'Core/Resource.php';
require_once 'Core/OAuth/Form.php';
require_once 'Zend/Controller/Action.php';

/**
 * This controller implementation is a full OAuth request gateway that may
 * be dropped in to any module by extension.
 * 
 * @author Michael Krotscheck
 */
class Core_OAuth_Controller extends Zend_Controller_Action {

	/**
	 * The oauth provider
	 * 
	 * @var OAuth
	 */
	private $provider;

	/**
	 * Predispatch Gesture
	 *
	 * @see Zend_Controller_Action::preDispatch()
	 */
	public function preDispatch()
	{
		parent::preDispatch();
		
		$this->provider = Core_Resource::locate('oauthprovider');
	}

	/**
	 * OAuth authorize action.
	 */
	public function authorizeAction()
	{
		$request = $this->getRequest();
		
		$form = new Core_OAuth_Form(array('action'=> '/api/oauth/authorize'));
		
		$oauth_token =  $request->getParam('oauth_token', null);
		$oauth_callback = $request->getParam('oauth_callback', 'oob');
		
		if ( $request->isPost() && $form->isValid($request->getParams()))
		{
			$oauth_verifier = $this->provider->authorize($oauth_token);
			
			if ( $oauth_verifier !== false )
			{
				if ( $oauth_callback == 'oob' )
				{
					$this->view->oauth_verifier = $oauth_verifier;
				}
				else
				{
					$params = array();
					$params['oauth_token'] = $oauth_token;
					$params['oauth_verifier'] = $oauth_verifier;
					
					$callback_url = sprintf( '%s?%s', $oauth_callback, http_build_query( $params ) );
					$this->_helper->redirector->gotoUrlAndExit($callback_url);
					exit();
				}
			}
		}
		else
		{
			$form->setDefault('oauth_token', $oauth_token);
			$form->setDefault('oauth_accept', 1);
			$form->setDefault('oauth_callback', $oauth_callback);
		}
		
		$this->view->form = $form;
	}

	/**
	 * This action handles the request_token endpoint and provides an authorized presenter
	 * of a consumer key with the appropriate auth token.
	 */
	public function requesttokenAction()
	{
		$this->_helper->layout->setLayout('blank');
		echo $this->provider->request_token();
	}

	/**
	 * This action handles the access_token action, returning a long lived acess token now
	 * that a user has decided to grant their access.
	 */
	public function accesstokenAction()
	{
		$this->_helper->layout->setLayout('blank');
		
		echo $this->provider->access_token();
	}

}
